package com.example.zookeeper.util;

import com.example.zookeeper.watch.DefaultWatch;
import com.example.zookeeper.watch.DefaultWatchCallBack;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * 创建Zookeeper对象
 * @author Vicente
 * @version 1.0
 * @date 2020/3/8 13:59
 */
public class ZookeeperUtils {
    private static final String url = "47.95.192.77:2181,47.95.192.77:2182,47.95.192.77:2183";  //远程服务端路径path
    private static DefaultWatch defaultWatch = new DefaultWatch();                              //watch回调函数，监听服务端状态，并将信息返回至客户端
    private static CountDownLatch latch = new CountDownLatch(1);
    private static ZooKeeper zooKeeper;

    /**
     * 基于Zookeeper API 异步模型
     * @return
     */
    public static ZooKeeper getZookeeperInstance(){
        try {
            zooKeeper = new ZooKeeper(url,1000,defaultWatch);
            defaultWatch.setCountDownLatch(latch);
            latch.await();          //此处阻塞，创建连接成功，zookeeper对象返回
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return zooKeeper;
    }
}
